package cn.edu.zafu.bigdata.rwx;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RhymingFinder {
    public static void main(String[] args) {
        Path filepath = Paths.get("files","words.txt");
        try {
            List<String> words = Files.readAllLines(filepath);
            Map<String, List<String>> rhymingWords = new RhymingFinder().findRhymingWords(words);
            for(List<String> group : rhymingWords.values()){
                if(group.size()>1) {
                    System.out.println(group);
                }
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    private Map<String, List<String>> findRhymingWords(List<String> words) {
        Map<String, List<String>> rhymes = new HashMap<>();
        for(String word: words){
            String rhyme = getRhyme(word, 3);
            rhymes.computeIfAbsent(rhyme, k -> new ArrayList<>()).add(word);
        }
        return rhymes;
    }

    private String getRhyme(String word, int length) {
        return word.length()<length?word:word.substring(word.length()-length);
    }
}
